﻿import { Injectable } from 'angular2/core';
import { Http, Response, Request, Headers } from 'angular2/http';
import { Todo } from '../domain/todo';

@Injectable()
export class TodoStore {
    private _baseUri: string = 'http://localhost:53990/api/todo';
    private _http: Http;
    private _currentTopic;
    topics: Array<Todo> = [];
    todos: Array<Todo> = [];

    constructor(public http: Http) {

        this.http.get(this._baseUri)
            .subscribe(res => {
                var data: any = res.json();

                this.topics = data.map((todo: { Id: Number, ParentId: Number, Title: String, Completed: Boolean, GroupName: String, SortOrder: Number }) => {
                    let ret = new Todo(todo.Title);
                    ret.Id = todo.Id;
                    ret.GroupName = todo.GroupName;
                    ret.ParentId = todo.ParentId;
                    ret.SortOrder = todo.SortOrder;
                    ret.Completed = todo.Completed;
                    return ret;
                });
            },
            error => {
                if (error.status == 401) {
                    // this.utilityService.navigateToSignIn();
                }

                console.log('Error: ' + error)
            },
            () => {
                this._currentTopic = this.topics[0].Id;
                this.http.get(this._baseUri + "?completed=" + false + "&parentId=" + this._currentTopic)
                    .subscribe(res => {
                        var data: any = res.json();

                        this.todos = data.map((todo: { Id: Number, ParentId: Number, Title: String, Completed: Boolean, GroupName: String, SortOrder: Number }) => {
                            let ret = new Todo(todo.Title);
                            ret.Id = todo.Id;
                            ret.GroupName = todo.GroupName;
                            ret.ParentId = todo.ParentId;
                            ret.SortOrder = todo.SortOrder;
                            ret.Completed = todo.Completed;
                            return ret;
                        });
                    },
                    error => {
                        if (error.status == 401) {
                            // this.utilityService.navigateToSignIn();
                        }

                        console.log('Error: ' + error)
                    },
                    () => console.log("Success"))
            });

   
    }

    get(completed, id) {
        
        var url = this._baseUri + "?completed=" + completed;
        
        if (id)
        {
            this._currentTopic = id;
            url = url + "&parentId=" + id;
        }
        else
            url = url + "&parentId=" + this._currentTopic;

        console.log(url);

        return this.http.get(url)
            .subscribe(res => {
                var data: any = res.json();

                this.todos = data.map((todo: { Id: Number, ParentId: Number, Title: String, Completed: Boolean, GroupName: String, SortOrder: Number }) => {
                    let ret = new Todo(todo.Title);
                    ret.Id = todo.Id;
                    ret.GroupName = todo.GroupName;
                    ret.ParentId = todo.ParentId;
                    ret.SortOrder = todo.SortOrder;
                    ret.Completed = todo.Completed;
                    return ret;
                });
            },
            error => {
                if (error.status == 401) {
                    // this.utilityService.navigateToSignIn();
                }

                console.log('Error: ' + error)
            },
            () => console.log("Success"));


    }

    allCompleted() {
        return this.todos.length === this.getCompleted().length;
    }

    setAllTo(completed: Boolean) {

        for (var i = 0, len = this.todos.length; i < len; i++) {
           var t = this.todos[i];
           t.Completed = false;
           this.toggleCompletion(t);
        }
    }

    removeCompleted() {
        this.todos = this.getWithCompleted(false);
    }

    getRemaining() {
        return this.getWithCompleted(false);
    }

    getCompleted() {
        return this.getWithCompleted(true);
    }

    update(todo: Todo)
    {
        let headers = new Headers({ 'Content-Type': 'application/json' });
        this.http.put(this._baseUri + "/" + todo.Id.toString(), JSON.stringify(todo), { headers: headers })
            .subscribe(res => {
                console.log("!");
            },
            error => console.log('There was an error: ' + error));
    }


    toggleCompletion(todo: Todo) {

        todo.Completed = !todo.Completed;
        console.log(todo.Completed);

        let headers = new Headers({ 'Content-Type': 'application/json' });
        this.http.put(this._baseUri + "/" + todo.Id.toString(), JSON.stringify(todo), { headers: headers })
            .subscribe(res => {
                this.todos.splice(this.todos.indexOf(todo), 1);
                console.log("!");
            },
            error => console.log('There was an error: ' + error));
    }

    remove(todo: Todo) {

        if (todo.Id != 0) {
            return this.http.delete(this._baseUri + "/" + todo.Id.toString())
                .subscribe(res => {
                    this.todos.splice(this.todos.indexOf(todo), 1);
                    console.log(res.json());
                },
                error => console.log('There was an error: ' + error)
                );
        }
    }

    add(title: String) {
        var todo = new Todo(title);
        todo.ParentId = this._currentTopic;

        let headers = new Headers({ 'Content-Type': 'application/json' });
        this.http.post(this._baseUri, JSON.stringify(todo), { headers: headers })
            .subscribe(res => {
                console.log(res.json());
                this.todos.unshift(res.json());
            },
            error => console.log('There was an error: ' + error)
            );
    }

    private getWithCompleted(completed: Boolean) {
        return this.todos.filter((todo: Todo) =>  todo.Completed === completed );
    }
}
